<template>
  <div class="page-container">
    <el-card shadow="never">
      <!-- 搜索 + 新增 -->
      <div style="margin-bottom: 20px; display: flex; justify-content: space-between;">
        <el-form :inline="true" :model="{ tagName: searchName }" @submit.prevent="handleSearch">
          <el-form-item label="标签名称">
            <el-input v-model="searchName" placeholder="请输入标签名称" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>

        <el-button type="primary" @click="showAddDialog = true">新增标签</el-button>
      </div>

      <!-- 标签表格 -->
      <el-table :data="tableData" border stripe style="width: 100%" v-loading="loading">
        <el-table-column align="center" prop="name" label="标签名称" />
        <el-table-column align="center" prop="createdAt" label="创建时间" width="300">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="150">
          <template #default="{ row }">
            <el-button size="small" type="danger" @click="deleteTag(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div style="margin-top: 20px; text-align: right">
        <el-pagination
            background
            layout="total, prev, pager, next"
            :total="total"
            :page-size="pageSize"
            :current-page="currentPage"
            @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 新增标签对话框 -->
    <el-dialog v-model="showAddDialog" title="新增标签" width="400px">
      <el-form :model="newTagForm" :rules="rules" ref="addFormRef" label-width="80px">
        <el-form-item label="标签名称" prop="name">
          <el-input v-model="newTagForm.name" placeholder="请输入标签名称" />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelAdd">取消</el-button>
          <el-button type="primary" @click="submitAdd">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue';
import request from '@/api/request';
import { ElMessage, ElMessageBox } from 'element-plus';

// 表格数据
const tableData = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const loading = ref(false);

// 搜索字段
const searchName = ref('');

// 新增相关
const showAddDialog = ref(false);
const newTagForm = reactive({ name: '' });
const addFormRef = ref(null);

// 表单校验规则
const rules = {
  name: [
    { required: true, message: '标签名称不能为空', trigger: 'blur' },
    { min: 1, max: 20, message: '长度在 1 到 20 个字符之间', trigger: 'blur' }
  ]
};

// 获取标签列表
const fetchData = () => {
  loading.value = true;
  request.get('/api/tag/list', {
    params: {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      name: searchName.value || undefined
    }
  })
      .then(res => {
        const data = res.data.data;
        tableData.value = data.records;
        total.value = data.total;
      })
      .catch(() => {
        tableData.value = [];
        total.value = 0;
      })
      .finally(() => {
        loading.value = false;
      });
};

// 分页切换
const handlePageChange = (page) => {
  currentPage.value = page;
  fetchData();
};

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1;
  fetchData();
};

// 重置搜索
const resetSearch = () => {
  searchName.value = '';
  handleSearch();
};

// 提交新增
const submitAdd = () => {
  addFormRef.value.validate(async valid => {
    if (!valid) return;

    try {
      const res = await request.post('/api/tag/add', newTagForm);
      if (res.data.code === 200) {
        ElMessage.success('新增成功');
        showAddDialog.value = false;
        fetchData(); // 刷新列表
      }
    } catch (error) {
      console.error('新增失败:', error);
    }
  });
};

// 取消新增
const cancelAdd = () => {
  showAddDialog.value = false;
  addFormRef.value.resetFields();
};

// 删除标签
const deleteTag = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除该标签吗？', '提示', {
      type: 'warning'
    });
    const res = await request.delete(`/api/tag/delete/${id}`);
    if (res.data.code === 200) {
      ElMessage.success('删除成功');
      fetchData(); // 刷新
    }
  } catch (error) {
    // 失败或取消
  }
};

// 初始化加载
fetchData();

// 时间格式化
const formatDate = (isoStr) => {
  return new Date(isoStr).toLocaleString('zh-CN', {
    year: 'numeric',
    month: 'short',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}
</script>

<style scoped>
.page-container {
  padding: 20px;
}
.dialog-footer button:first-child {
  margin-right: 10px;
}
</style>
